<template>
  <div class="wx-login">
    <!-- 登录对话框 -->
    <q-dialog v-model="dialogVisible">
      <q-card class="q-pa-md login-card">
        <q-card-section>
          <div class="text-h6 text-center">扫码登录</div>
        </q-card-section>

        <q-card-section class="scan-ercode">
          <div v-if="timeout" class="text-center expired" @click="scan">
            验证码已过期，请重新获取
          </div>
          <img v-else :src="wxUrl" width="250" @click="scan" />
          <span class="text-center">使用微信扫码绑定（登录）</span>
        </q-card-section>
      </q-card>
    </q-dialog>

    <!-- 注册/绑定对话框 -->
    <q-dialog v-model="registerVisible" @hide="clearTimer">
      <q-card class="q-pa-md register-card">
        <q-card-section>
          <div class="text-h6 text-center">注册或绑定</div>
        </q-card-section>

        <q-card-section>
          <div class="text-center">输入用户名密码，自动绑定现有用户或创建新用户</div>
          <q-form ref="ruleFormRef" @submit="registerEnter" class="q-gutter-md form-center">
            <q-input filled v-model="registerForm.username" label="用户名" />
            <q-input filled v-model="registerForm.password" type="password" label="密码" />
            <q-btn label="确认" type="submit" color="primary" class="full-width-btn" />
          </q-form>
        </q-card-section>
      </q-card>
    </q-dialog>

    <!-- 操作按钮 -->
    <div class="button-group">
      <q-btn label="扫码登录" @click="scan" color="primary" class="login-btn" />
      <q-btn label="解除绑定" @click="clear" color="warning" class="clear-btn" />
    </div>
  </div>
</template>

<script setup>
import { ref, nextTick } from 'vue';
import { getLoginPic, loginOrCreate, clearWx, register } from 'src/api/wx.js';
import { createUniqueId } from 'src/utils/createUniqueId.js';
import { useQuasar } from 'quasar';

const $q = useQuasar();
const wxUrl = ref('');
const timeout = ref(false);
const dialogVisible = ref(false);
const timer = ref(null);
const registerVisible = ref(false);
const registerForm = ref({
  username: '',
  password: '',
  loginFlag: ''
});

const scan = async () => {
  dialogVisible.value = true;
  const loginFlag = createUniqueId(6);
  const state = window.localStorage.getItem('token') || undefined;
  await nextTick();
  const res = await getLoginPic({ loginFlag, state });
  if (res.code === 0) {
    timeout.value = false;
    clearTimer();
    setTimeout(() => {
      timeout.value = true;
    }, 250 * 1000);
    wxUrl.value = `https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=${res.data.ticket}`;
    timer.value = setInterval(() => {
      polling(loginFlag, state);
    }, 2000);
  }
};

const polling = async (loginFlag, state) => {
  const res = await loginOrCreate({ loginFlag, state });
  if (res.code === 0) {
    $q.notify({ type: 'positive', message: res.msg });
    clearInterval(timer.value);
    timer.value = null;

    if (res.data.needRegister) {
      registerForm.value.loginFlag = loginFlag;

      // 显示二维码弹窗，要求用户扫码登录小程序
      qrDialogVisible.value = true; // 控制二维码弹窗的显示状态
      qrUrl.value = `https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=${res.data.qrTicket}`; // 设置二维码的 URL
    } else {
      dialogVisible.value = false;
    }
  }

  if (res.data.token && res.data.id) {
    // 保存 token 和 id 到 localStorage
    window.localStorage.setItem('token', res.data.token);
    window.localStorage.setItem('userId', res.data.id);

    // 显示登录成功消息
    $q.notify({ type: 'positive', message: res.msg });

    // 跳转到指定的路由（替换 'Home' 为目标路由名称或路径）
    $router.push({ name: 'Home' });
  } else {
    clearInterval(timer.value);
    timer.value = null;
  }
};


const clearTimer = () => {
  clearInterval(timer.value);
};

const clear = async () => {
  const res = await clearWx();
  if (res.code === 0) {
    $q.notify({ type: 'positive', message: res.msg });
  }
};

const registerEnter = async () => {
  const res = await register(registerForm.value);
  if (res.code === 0) {
    window.localStorage.setItem('token', res.data.token);
    window.location.reload();
  }
};
</script>

<style lang="scss" scoped>
.wx-login {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  min-height: 100vh;

  .button-group {
    display: flex;
    justify-content: center;
    gap: 20px;
    margin-top: 20px;
  }

  .login-btn, .clear-btn {
    width: 200px;
  }

  .scan-ercode {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;

    img {
      cursor: pointer;
      border: 1px dashed #ccc;
      border-radius: 4px;
      margin-bottom: 10px;
    }

    div.expired {
      color: red;
      cursor: pointer;
      border: 1px dashed #ccc;
      border-radius: 4px;
      padding: 10px;
      margin-bottom: 10px;
    }

    span {
      margin-top: 10px;
    }
  }

  .login-card, .register-card {
    max-width: 400px;
    width: 100%;
    text-align: center;
  }

  .form-center {
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  .full-width-btn {
    width: 100%;
  }
}
</style>
